package me.firstapp.bts.service.impl;

import java.util.Date;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import me.firstapp.bts.service.ApiClientJobService;
import me.firstapp.common.json.ListObject;
import me.firstapp.common.module.system.JsonApiClient;
import me.firstapp.common.utils.DateUtils;
import me.firstapp.spi.system.ApiClientService;

@Service
public class ApiClientJobServiceImpl implements ApiClientJobService {
	private static Logger logger = LoggerFactory.getLogger(ApiClientJobService.class);

	@Autowired
	private ApiClientService apiClientService;

	@Autowired
	private RedisTemplate<String, Object> redisTemplate;

	@Override
	public void updateCounts() {
		long start = System.currentTimeMillis();
		logger.info("..................开始批处理ApiClient..................");
		ListObject<JsonApiClient> clientsJson = apiClientService.findAll();
		if (clientsJson != null) {
			List<JsonApiClient> clients = clientsJson.getItems();
			if (clients != null && !clients.isEmpty()) {
				for (JsonApiClient client : clients) {
					Long counts = (Long) redisTemplate.opsForValue().get("apiClientCountsCache_"+client.getApiKey());
					client.setYesCounts(counts);
					apiClientService.updateApiClient(client.getId(), counts, null, null);
					Long dateTime = DateUtils.getBeforeOrNextDay(new Date(), -1).getTime();
					apiClientService.addApiClientRecord(client.getId(), dateTime, counts);
					redisTemplate.opsForValue().set("apiClientCountsCache_"+client.getApiKey(), 0L);
				}
			}
		}
		logger.info(
				"..................结束批处理ApiClient....................耗时===》" + (System.currentTimeMillis() - start));
	}

}
